package com.kevin.j2eeToolBox.thread;

public class SynchronizedTest1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SynchronizedTest1 test = new SynchronizedTest1();
		test.excute();
	}

	public void excute() {

		final Function function = new Function();

		new Thread() {
			@Override
			public void run() {
				try {

					for (int i = 0; i < 5; i++) {
						function.foo1();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					for (int i = 0; i < 5; i++) {
						function.foo2();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
	}

	class Function {

		private Boolean isExcute = false;

		public void foo1() throws InterruptedException {

			synchronized (this) {
				if (isExcute) {
					this.wait();
				}

				for (int i = 0; i < 5; i++) {
					Thread.sleep(100);
					System.out.println("Hello " + i);
				}

				this.isExcute = true;
				this.notify();

			}

		}

		public void foo2() throws InterruptedException {

			synchronized (this) {

				if (!isExcute) {
					this.wait();
				}

				for (int i = 0; i < 10; i++) {
					Thread.sleep(100);
					System.out.println("World " + i);
				}

				this.isExcute = false;
				this.notify();

			}
		}
	}

}
